# -*- coding: utf-8 -*-
# @文件名称 : menu.py
# @创建时间 : 2024-11-17
# @功能描述 : 菜单功能程序，存放附加功能



import platform
import concurrent.futures
import psutil
import wmi
import math
import socket
import datetime
import tkinter as tk
from tkinter import messagebox,scrolledtext
import subprocess
import threading
from utils import get_icon_path, center_window
import queue


# 显示系统信息
def show_system_info():
    # 获取当前系统信息
    def get_system_info():
        # 获取操作系统安装日期
        def get_os_install_date():
            try:
                import winreg
                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion") as key:
                    install_date = winreg.QueryValueEx(key, "InstallDate")[0]
                    install_date = datetime.datetime.fromtimestamp(install_date).strftime('%Y/%m/%d/%A')
                    return install_date
            except Exception as e:
                return "无法获取安装日期"

        # 获取CPU信息
        def get_cpu_info():
            c = wmi.WMI()
            for processor in c.Win32_Processor():
                cpu_info = {
                    "品牌和型号": processor.Name,
                    "核心数": processor.NumberOfCores,
                    "线程数": processor.NumberOfLogicalProcessors,
                    "最大频率": f"{processor.MaxClockSpeed} MHz",
                    "当前频率": f"{psutil.cpu_freq().current} MHz"
                }
                formatted_info = (f"{cpu_info['品牌和型号']}，"
                                  f"{cpu_info['核心数']}核心{cpu_info['线程数']}线程")
                return formatted_info

        system_info = {
            "\n"
            "操作系统": platform.system()+ " " + platform.release(),  # 操作系统+内核版本
            "系统版本": platform.version(),
            "安装日期": get_os_install_date(),
            "主机名称": platform.node(),
            "网络地址": socket.gethostbyname(socket.gethostname()),
            "CPU架构": platform.processor(),
            # 例如：Intel64 Family 6 Model 158 Stepping 10, GenuineIntel 表示这是一个 Intel64 架构的 CPU，属于第 6 家族，型号 158，步进 10。
            "CPU信息": get_cpu_info(),
            "运行内存": f"{math.ceil(psutil.virtual_memory().total / (1024 ** 3))} GB",
            "系统类型": f"{platform.architecture()[0]}操作系统，基于{platform.machine()}的处理器",
            "操作系统版本": platform.platform()
        }
        return system_info

    system_info = get_system_info()
    info_text = "\n".join([f"{key}: {value}" for key, value in system_info.items()])
    messagebox.showinfo("系统信息", info_text)



# 全局变量来管理线程
executor = None
stop_event = threading.Event()

def show_network_info(root):
    """创建子窗口并显示网络连接信息"""
    global executor, stop_event
    stop_event.clear()  # 重置停止事件

    if not executor:
        executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)

    network_window = tk.Toplevel(root)  # 创建新窗口显示网络信息
    network_window.title("网络配置信息")  # 设置窗口标题
    center_window(network_window, 650, 400)  # 设置窗口居中和大小
    network_window.iconbitmap(get_icon_path())  # 设置窗口图标
    network_window.resizable(False, False)  # 禁止调整窗口大小
    network_window.transient(root)  # 将新窗口置于主界面之上
    network_window.grab_set()  # 禁止点击主界面

    text_area = scrolledtext.ScrolledText(network_window, wrap=tk.WORD, state=tk.DISABLED)  # 创建带滚动条的文本区域，设置为不可编辑
    text_area.pack(side=tk.TOP, fill=tk.BOTH, expand=True)  # 填充窗口

    def log_func(message):
        text_area.config(state=tk.NORMAL)  # 临时设置为可编辑
        text_area.insert(tk.END, message)
        text_area.see(tk.END)
        text_area.config(state=tk.DISABLED)  # 重新设置为不可编辑

    def clear_text_area():
        text_area.config(state=tk.NORMAL)  # 临时设置为可编辑
        text_area.delete(1.0, tk.END)  # 清空 ScrolledText 控件的内容
        text_area.config(state=tk.DISABLED)  # 重新设置为不可编辑

    def run(queue):
        try:
            while not stop_event.is_set():  # 检查停止事件
                command_output = subprocess.run(
                    ["ipconfig", "/all"],
                    capture_output=True,
                    text=True,
                    creationflags=subprocess.CREATE_NO_WINDOW  # 防止命令行窗口弹出
                )
                if command_output.returncode != 0:
                    queue.put(f"查看网络连接信息失败: {command_output.stderr}\n")
                else:
                    queue.put("网络连接信息:\n")
                    queue.put(command_output.stdout)
                break  # 只执行一次
        except Exception as e:
            queue.put(f"查看网络连接信息时发生错误: {str(e)}\n")

    def show_network_info_content():
        clear_text_area()  # 清空 ScrolledText 控件的内容
        q = queue.Queue()
        future = executor.submit(run, q)
        check_queue(q, future)

    def check_queue(q, future):
        while not q.empty():
            message = q.get()
            log_func(message)
        if not future.done():
            network_window.after(100, check_queue, q, future)

    def close_window():
        global executor, stop_event
        stop_event.set()  # 设置停止事件
        if executor and not executor._shutdown:
            if not executor._work_queue.empty():
                executor.shutdown(wait=True)  # 等待所有任务完成
        network_window.destroy()  # 关闭查看窗口

    close_button = tk.Button(network_window, text="关闭", command=close_window)  # 创建关闭按钮
    close_button.pack(side=tk.BOTTOM, fill=tk.X)  # 放置按钮

    # 初始显示网络信息
    show_network_info_content()


# 测试
if __name__ == "__main__":
    #show_system_info()
    root = tk.Tk()
    show_network_info(root)
    root.mainloop()
